package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.jdbc.Null;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class SystemLogUtil {

    @Autowired
    ISystemLogService systemLogService;


    public void writeLog(JoinPoint joinPoint){
        //不记录日志的操作方法
        if (joinPoint.getTarget() instanceof ISystemLogService){
            return;
        }
        SystemLog log = new SystemLog();
        //操作时间
        log.setOpTime(new Date());
        //当前用户
        log.setOpUser(UserContext.getCurrentUser());
        //操作ip
        log.setOpIp(UserContext.getRequest().getRemoteAddr());
        System.out.println(log.getOpIp());
        //类名
        String className = joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //操作的方法
        log.setFunction(className+":"+methodName);
        //传入的参数
        try {
            log.setParams(new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
            //保存到数据库
            systemLogService.insert(log);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

}
